#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define el '\n'
using namespace std;
using namespace __gnu_pbds;
typedef tree<int, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
const int N = 1e3 + 7;
const int MOD = 1e9 + 7;
int dx[] = {1, -1, 0, 0, -1, -1, 1, 1};
int dy[] = {0, 0, 1, -1, 1, -1, 1, -1};
// think very carefully before writing a line of code //
// enjoy the problems //
// never focus on performance during a contest //
int dp[N][N][4];
int A[N][N];
int n, m;
void doWork() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> A[i][j];
}
}
// coming from 1,1 and moving left and down
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j][0] = A[i][j] + max(dp[i - 1][j][0], dp[i][j - 1][0]);
}
}
// coming from n, 1 and moving up and right
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= m; j++) {
dp[i][j][1] = A[i][j] + max(dp[i + 1][j][1], dp[i][j - 1][1]);
}
}
// coming from n, m and moving up and left
for (int i = n; i >= 1; i--) {
for (int j = m; j >= 1; j--) {
dp[i][j][2] = A[i][j] + max(dp[i + 1][j][2], dp[i][j + 1][2]);
}
}
// coming from 1, m and moving left and down
for (int i = 1; i <= n; i++) {
for (int j = m; j >= 1; j--) {
dp[i][j][3] = A[i][j] + max(dp[i - 1][j][3], dp[i][j + 1][3]);
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (i - 1 >= 1 && i + 1 <= n && j - 1 >= 1 && j + 1 <= m) {
ans = max(ans, dp[i - 1][j][0] + dp[i + 1][j][2] + dp[i][j + 1][3] + dp[i][j - 1][1]);
ans = max(ans, dp[i - 1][j][3] + dp[i + 1][j][1] + dp[i][j + 1][2] + dp[i][j - 1][0]);
}
}
}
cout << ans;
}
signed main() {
fast
// freopen("snakes.in", "r", stdin);
// freopen("snakes.out", "w", stdout);
int testcases = 1;
// cin >> testcases;
for (int i = 1; i <= testcases; i++) {
doWork();
}
}
237. Delete Node in a Linked List | 27. Remove Element |
39. Combination Sum | 378. Kth Smallest Element in a Sorted Matrix |
162. Find Peak Element | 1529A - Eshag Loves Big Arrays |
19. Remove Nth Node From End of List | 925. Long Pressed Name |
1051. Height Checker | 695. Max Area of Island |
402. Remove K Digits | 97. Interleaving String |
543. Diameter of Binary Tree | 124. Binary Tree Maximum Path Sum |
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts | 501A - Contest |
160A- Twins | 752. Open the Lock |
1535A - Fair Playoff | 1538F - Interesting Function |
1920. Build Array from Permutation | 494. Target Sum |
797. All Paths From Source to Target | 1547B - Alphabetical Strings |
1550A - Find The Array | 118B - Present from Lena |
27A - Next Test | 785. Is Graph Bipartite |
90. Subsets II | 1560A - Dislike of Threes |